package com.linuxgt.laboratory.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * Created by liuteng on 17-12-28.
 */
@Aspect
@Component
public class HttpAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * com.linuxgt.laboratory.*Controller.*(..))")
    public void HttpLog() {
        logger.info("http log");
    }

    @Before("HttpLog()")
    public void doBefore(JoinPoint joinPoint) {

        logger.info("http log before start");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = attributes.getRequest();

        logger.info("URL:{}", request.getRequestURL());

        logger.info("HTTP_METHOD:{}", request.getMethod());

        logger.info("IP : " + request.getRemoteAddr());

        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature
                ().getName());

        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));


        Enumeration<String> enu = request.getParameterNames();

        while (enu.hasMoreElements()) {

            String paraName = enu.nextElement();

            System.out.println(paraName + ": " + request.getParameter(paraName));

        }

    }

    @AfterReturning("HttpLog()")
    public void doAfterReturning(JoinPoint joinPoint) {
        logger.info("WebLogAspect.doAfterReturning()");
    }
}
